/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.mvc
{
	import com.puny.mvc.models.Model;
	
	import flash.events.EventDispatcher;
	
	public class ListenerManager extends Object
	{
		private var _handlers:Array = new Array();
		public function ListenerManager() {
			super();
		}
		
		public function add(type:String, listener:Function):void {
			var model:Model = new Model();
			model.type = type;
			model.listener = listener;
			_handlers.push(model);
		}
		
		public function remove(type:String, listener:Function):void {
			var length:int = _handlers.length;
			for (var index:int = 0;index < length;index++) {
				var model:Model = _handlers[index];
				if (model.type == type && model.listener == listener) {
					model.type = null;
					model.listener = null;
					_handlers.splice(index,1);
					break;
				}
			}
		}
		
		public function cleanUpListeners(dispatcher:EventDispatcher):void {
			while(_handlers.length > 0) {
				var model:Model = _handlers.pop();
				trace("Removed \""+model.type+"\" event listener from",dispatcher);
				dispatcher.removeEventListener(model.type,model.listener);
				model.cleanUp();
				model.type = null;
				model.listener = null;
			}
		}
		
	}
}